package skean.apserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.R.anim;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements Callback, OnClickListener {
	private ListView lsvBSInfo;
	private Button btnStart, btnStop, btnGetinfo;
	private Button btn2G, btn3G, btn4G;
	private TextView txvCount;
	private ProgressDialog dlgProgress;
	private AlertDialog dlgConfirm;

	private Timer timer;
	private WifiAdmin admin;
	private Handler mHandler;
	private List<String> linkedIpList;
	private List<Socket> LinkedSocketList;
	private List<String> baseinfoList;
	private BSAdapter adapter;
	private String nwType;

	public static final int MSG_NOTIFI = 1;
	public static final int MSG_COUNT = 2;
	public static final int MSG_RESCAN = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnStart = (Button) findViewById(R.id.btn_start);
		btnStop = (Button) findViewById(R.id.btn_stop);
		btnGetinfo = (Button) findViewById(R.id.btn_getinfo);
		btn2G = (Button) findViewById(R.id.btn_check2g);
		btn3G = (Button) findViewById(R.id.btn_check3g);
		btn4G = (Button) findViewById(R.id.btn_check4g);
		txvCount = (TextView) findViewById(R.id.txv_count);
		lsvBSInfo = (ListView) findViewById(R.id.lsv_linked);
		initDialog();

		btnStart.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnGetinfo.setOnClickListener(this);
		btn2G.setOnClickListener(this);
		btn3G.setOnClickListener(this);
		btn4G.setOnClickListener(this);
		baseinfoList = new ArrayList<String>();
		adapter = new BSAdapter();
		lsvBSInfo.setAdapter(adapter);

		mHandler = new Handler(this);
		admin = new WifiAdmin(this);
	}
	private void initDialog() {
		dlgProgress = new ProgressDialog(this);
		dlgProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dlgProgress.setMessage("查询中...");
		dlgProgress.setCancelable(true);
		dlgConfirm = new AlertDialog.Builder(this).setMessage("切换基站信息需要等待几分钟,是否继续?")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (timer != null) {
						timer.cancel();
						timer = null;
					}
					new Thread() {
						@Override
						public void run() {
							getSockets();
							for (Socket socket : LinkedSocketList) {
								new Thread(new RebootTask(socket)).start();
							}
						}

					}.start();
				}
			}).setNegativeButton("取消", null).create();
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_NOTIFI:
			adapter.notifyDataSetChanged();
			break;
		case MSG_COUNT:
			txvCount.setText(msg.arg1 + "");
			break;
		case MSG_RESCAN:
			if (timer == null) {
				timer = new Timer();
				timer.schedule(new ScanTask(), 0, 3000);
			}
			break;
		}
		return false;
	}

	private class RebootTask implements Runnable {
		private Socket socket;

		public RebootTask(Socket socket) {
			this.socket = socket;
		}
		public void run() {
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(socket.getOutputStream());
				Log.i("服务端", "发出请求");
				writer.println("reboot" + nwType);
				writer.flush();
			}
			catch (Exception e) {
				Log.i("服务端", "连接客户端出错");
			}
			finally {
				try {
					writer.close();
					socket.close();
				}
				catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}
	private class GetInfoTask implements Runnable {
		private Socket socket;

		public GetInfoTask(Socket socket) {
			this.socket = socket;
		}
		public void run() {
			BufferedReader reader = null;
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(socket.getOutputStream());
				reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				Log.i("服务端", "发出请求");
				writer.println("get");
				writer.flush();
				String line = null;
				while (true) {
					line = reader.readLine();
					if (line != null) {
						Log.i("服务端", "收到客户端的返回");
						baseinfoList.add(line);
						mHandler.sendEmptyMessageDelayed(MSG_NOTIFI, 1000);
						mHandler.sendEmptyMessageDelayed(MSG_RESCAN, 3000);
						break;
					}
				}
			}
			catch (Exception e) {
				Log.i("服务端", "连接客户端出错");
			}
			finally {
				try {
					writer.close();
					reader.close();
					socket.close();
				}
				catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}
	private class ScanTask extends TimerTask {

		@Override
		public void run() {
			// 获取连接上的ip并且检查连接状况
			admin.checkLinked();
			try {
				Thread.sleep(1500);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			linkedIpList = admin.getLinked();
			Message msg = new Message();
			msg.what = MSG_COUNT;
			msg.arg1 = linkedIpList.size();
			mHandler.sendMessage(msg);
		}

	}

	private void getSockets() {
		LinkedSocketList = new ArrayList<Socket>();
		for (String ip : linkedIpList) {
			try {
				Socket socket = new Socket();
				socket.connect(new InetSocketAddress(ip, 12345), 500);
				LinkedSocketList.add(socket);
			}
			catch (UnknownHostException e) {
				e.printStackTrace();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_start:
			btnStop.setEnabled(true);
			btnGetinfo.setEnabled(true);
			btnStart.setEnabled(false);
			admin.setWifiApEnabled(true);
			timer = new Timer();
			timer.schedule(new ScanTask(), 0, 3000);
			break;

		case R.id.btn_stop:
			btnStop.setEnabled(false);
			btnGetinfo.setEnabled(false);
			btnStart.setEnabled(true);
			admin.setWifiApEnabled(false);
			break;
		case R.id.btn_getinfo:
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			baseinfoList = new ArrayList<String>();
			adapter.notifyDataSetChanged();
			new Thread() {
				@Override
				public void run() {
					getSockets();
					for (Socket socket : LinkedSocketList) {
						new Thread(new GetInfoTask(socket)).start();
					}
				}

			}.start();
			break;
		case R.id.btn_check2g:
			nwType = "2g";
			dlgConfirm.show();
			break;
		case R.id.btn_check3g:
			dlgConfirm.show();
			nwType = "3g";
			break;
		case R.id.btn_check4g:
			dlgConfirm.show();
			nwType = "4g";
			break;

		}
	}
	private class BSAdapter extends BaseAdapter {

		public int getCount() {
			return baseinfoList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(MainActivity.this, android.R.layout.simple_list_item_1,
					null);
			}
			((TextView) convertView).setText(baseinfoList.get(position));
			return convertView;
		}

	}
}
